package generator.mybatis.plugin;

import org.mybatis.generator.api.FullyQualifiedTable;
import org.mybatis.generator.api.GeneratedJavaFile;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.Plugin;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.Method;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;

/**
 * 2019/4/23
 * 生成service层
 *
 * @author machuanpeng
 */
public class MyServicePlugin extends PluginAdapter {
    /**
     * 包路径
     */
    private String targetPackage;
    /**
     * 目标
     */
    private String targetProject;

    private IntrospectedTable introspectedTable;

    @Override
    public boolean validate(List<String> warnings) {
        targetPackage = properties.getProperty("targetPackage");
        targetProject = properties.getProperty("targetProject");
        if (!stringHasValue(targetProject)) {
            targetProject = "mybatis/src/main/java";
        }
        return stringHasValue(targetPackage);
    }

    /**
     * 添加文件.
     * 2019/6/14
     *
     * @param introspectedTable introspectedTable
     * @return java.util.List<org.mybatis.generator.api.GeneratedJavaFile>
     * @author machuanpeng
     */
    @Override
    public List<GeneratedJavaFile> contextGenerateAdditionalJavaFiles(IntrospectedTable introspectedTable) {
        List<GeneratedJavaFile> generatedJavaFiles = new ArrayList<>();
        this.introspectedTable = introspectedTable;
        FullyQualifiedTable fullyQualifiedTable = introspectedTable.getFullyQualifiedTable();

        //model名称
        String domainName = fullyQualifiedTable.getDomainObjectName();

        //service层接口
        FullyQualifiedJavaType interfaceType = new FullyQualifiedJavaType(targetPackage + "." + domainName + "Service");
        Interface interfaze = new Interface(interfaceType);
        interfaze.setVisibility(JavaVisibility.PUBLIC);

        Plugin plugin = context.getPlugins();
        if (plugin.clientGenerated(interfaze, null, introspectedTable)) {
            List<Method> methods = interfaze.getMethods();
            Set<FullyQualifiedJavaType> fullyQualifiedJavaTypes = interfaze.getImportedTypes();
            fullyQualifiedJavaTypes.removeAll(fullyQualifiedJavaTypes);
            methods.removeAll(methods);
            GeneratedJavaFile generatedJavaFile = new GeneratedJavaFile(interfaze, targetProject, context.getJavaFormatter());
            generatedJavaFiles.add(generatedJavaFile);
        }
        return generatedJavaFiles;
    }

}
